<div class="layui-fluid" lig-title="role-list" lay-title="角色列表">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-btn-container nepadmin-pad-t10 nepadmin-pad-l10">
                <form lay-filter="lig-role-searchForm">
                    <input type="hidden" name="appId"/>
                    <input type="hidden" name="parentId" value="root"/>
                </form>
            </div>
            <table class="layui-table layui-form" lay-filter="lig-role-table"></table>
        </div>
    </div>
</div>

<script type="text/html" id="tpl-role-modify">
    <form class="layui-form" lay-filter="lig-saveForm" style="padding: 20px 20px 0 0;">
        <input type="hidden" name="roleId" value="{{d.roleId}}"/>
        <div class="layui-form-item">
            <label class="layui-form-label ligui-form-item-required" lig-lang="role-roleName">名称</label>
            <div class="layui-input-block">
                <input type="text" name="roleName" lay-verify="required" autocomplete="off" class="layui-input"
                        value='{{d.roleName}}'>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" lig-lang="role-roleCode">编码</label>
            <div class="layui-input-block">
                <input type="text" name="roleCode" autocomplete="off"
                       class="layui-input" value="{{d.roleCode}}">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" lig-lang="role-remark">备注</label>
            <div class="layui-input-block">
                <input type="text" name="remark" autocomplete="off"
                       class="layui-input" value="{{d.remark}}">
            </div>
        </div>
    </form>
</script>
<script type="text/html" id="tpl-role-add">
    <form class="layui-form" lay-filter="lig-saveForm" style="padding: 20px 20px 0 0;">
        <input type="hidden" name="parentId"/>
        <div class="layui-form-item">
            <label class="layui-form-label ligui-form-item-required" lig-lang="role-roleName">名称</label>
            <div class="layui-input-block">
                <input type="text" name="roleName" lay-verify="required" autocomplete="off" class="layui-input"
                        value=''>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" lig-lang="role-roleCode">编码</label>
            <div class="layui-input-block">
                <input type="text" name="roleCode" autocomplete="off"
                       class="layui-input" value="">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label" lig-lang="role-remark">备注</label>
            <div class="layui-input-block">
                <input type="text" name="remark" autocomplete="off"
                       class="layui-input" value="">
            </div>
        </div>
    </form>
</script>
<script type="text/html" id="tpl-role-res-add">
    <form class="layui-form" lay-filter="lig-saveForm" style="padding: 10px 20px 0 20px;">
        <input type="hidden" name="roleId"/>
        <div lay-filter="lig-role-res-tree"></div>
    </form>
</script>
<script type="text/html" id="tpl-row-toolBar-user">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="lig-choose" lig-lang="btn-choose">选择</a>
</script>
<script type="text/html" id="tpl-role-user-add">
    <div style="padding: 10px 20px 0 20px;">
        <form class="layui-form" lay-filter="lig-role-searchForm">
            <input type="hidden" name="roleId"/>
            <div class="layui-inline">
                <label class="layui-form-label" lig-lang="user-userName">用户名</label>
                <div class="layui-inline">
                    <input type="text" class="layui-input" name="userName"/>
                </div>
            </div>
            <div class="layui-inline">
                <div class="layui-row layui-col-space10">
                    <div class="layui-col-xs6">
                        <div class="layui-btn layui-btn-sm layui-btn-fluid"
                             lay-filter="lig-user-search" lig-lang="btn-search">查询
                        </div>
                    </div>
                    <div class="layui-col-xs6">
                        <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary" lig-lang="btn-reset">重置</button>
                    </div>
                </div>
            </div>
        </form>
        <table lay-filter="lig-user-table"></table>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
            <legend lig-lang="role-chooseUserInfo">已选择用户</legend>
        </fieldset>
        <div class="layui-btn-container tag" lay-filter="lig-user-tag" lay-allowclose="true"></div>
        <form lay-filter="lig-saveForm"></form>
    </div>
</script>
<script type="text/html" id="tpl-user-tag">
    {{#  layui.each(d.data, function(index, item){ }}
    <button lay-id="{{item.userId}}" type="button" class="tag-item">{{item.userName}}</button>
    {{#  }); }}
</script>
<script>
    layui.use(['jquery', 'form', 'laytpl', 'eleTree', 'treeTable', 'tag', 'lig'], function ($, form, laytpl, eleTree, treeTable, tag, lig) {
        var _eleTree;

        form.render();

        requestData();
        function requestData() {
            lig.ajaxget({
                url: 'uc/role/tree/list',
                success: function (res) {
                    showData(res.data);
                }
            });
        }

        function showData(data) {
            treeTable.render({
                elem: '[lay-filter="lig-role-table"]',
                data: data,
                icon_key: 'roleName',
                primary_key: 'roleId',
                parent_key: 'parentId',
                end: function(e){
                    lig.filter($('[lay-filter="lig-role-table"]'));
                    lig.filterAction($('[lay-filter="lig-role-table"]'));
                    form.render();
                },
                cols: [
                    {
                        key: 'roleName',
                        title: '<span lig-lang="role-roleName">名称</span>',
                        width: '30%',
                        template: function(item){
                            if (item.level == 0){
                                return '<span style="color:red;">'+item.roleName+'</span>';
                            } else if (item.level == 1){
                                return '<span style="color:green;">'+item.roleName+'</span>';
                            }
                            return '<span style="color:#aaa;">'+item.roleName+'</span>';
                        }
                    },
                    {
                        key: 'remark',
                        title: '<span lig-lang="role-remark">备注</span>',
                        width: '30%',
                        align: 'center',
                    },
                    {
                        key: 'roleCode',
                        title: '<span lig-lang="role-roleCode">编码</span>',
                        width: '10%',
                        align: 'center',
                    },
                    {
                        title: '<span lig-lang="label-opt">操作</span>',
                        align: 'center',
                        template: function(item){
                            console.log(item)
                            if (item.level == 0) {
                               return '<a lay-filter="lig-role-add-child" lig-lang="btn-addRoleChild">添加子项</a>';
                            }
                            return '<a lay-filter="lig-role-user-add" lig-lang="btn-addRoleUser">关联用户</a> | <a lay-filter="lig-role-add-child" lig-lang="btn-addRoleChild">添加子项</a> | <a lay-filter="lig-role-res-add" lig-lang="btn-addRoleRes">权限</a> | <a lay-filter="lig-role-modify" lig-lang="btn-modify">修改</a> | <a lay-filter="lig-role-remove" lig-lang="btn-delete">删除</a>';
                            //return '<a lay-filter="lig-role-add-child">添加子项</a> | <a lay-filter="lig-role-res-add">权限</a> | <a lay-filter="lig-role-modify">修改</a> | <a lay-filter="lig-role-remove">删除</a>';
                        }
                    }
                ]
            });
            treeTable.on('tree(lig-role-add-child)',function(data){
                var _parentId = data.item.roleId;
                dialogSaveFormRes({title: '<span lig-lang="role-addRoleChild">添加子项</span>', parentId:_parentId});
            });
            treeTable.on('tree(lig-role-modify)',function(data){
                lig.ajaxget({
                    url: 'uc/role/' + data.item.roleId,
                    success: function (result) {
                        laytpl($('#tpl-role-modify').html()).render(result.data, function (html) {
                            lig.dialog({
                                content: html,
                                title: '<span lig-lang="role-modifyRole">修改角色</span>',
                                area: ['50%', 'auto'],
                                saveUrl: 'uc/role/modify',
                                onOpened: function () {
                                },
                                onCompleted: function () {
                                    requestData();
                                }
                            });
                        });
                    }
                })
            });
            treeTable.on('tree(lig-role-remove)',function(data){
                lig.remove({
                    url: 'uc/role/remove',
                    data: {ids: data.item.roleId},
                    completed: function () {
                        requestData();
                    }
                });
            });
            treeTable.on('tree(lig-role-res-add)',function(data){
                lig.dialog({
                    content: $('#tpl-role-res-add').html(),
                    title: '<span lig-lang="role-addUserRes">关联权限</span>',
                    area: ['40%', '90%'],
                    saveUrl: 'uc/role/res/add',
                    onSave: function(data) {
                        var _nodes = _eleTree.getChecked(false, true);
                        var _resIds = '';
                        $.each(_nodes, function (i, it) {
                            _resIds += it.id + ',';
                        });
                        data.resIdList = _resIds.substring(0, _resIds.length - 1);
                        return data;
                    },
                    onOpened: function () {
                        var _saveForm = $('[lay-filter="lig-saveForm"]'), _roleId = data.item.roleId;;
                        _saveForm.find('input[name="roleId"]').val(_roleId);
                        loadRoleResTree(_roleId);
                    },
                    onCompleted: function () {
                        //requestData();
                    }
                });
            });
            treeTable.on('tree(lig-role-user-add)',function(res){
                lig.dialog({
                    content: $('#tpl-role-user-add').html(),
                    title: '<span lig-lang="role-addRoleUser">关联用户</span>',
                    area: ['60%', '80%'],
                    saveUrl: 'uc/role/user/add',
                    onSave: function(data) {
                        var userIds = '';
                        $('[lay-filter="lig-user-tag"]').find('button').each(function () {
                            userIds += ',' + $(this).attr('lay-id');
                        });
                        data.roleId = res.item.roleId;
                        data.userIdList = userIds.substring(1);
                        return data;
                    },
                    onOpened: function () {
                        var _saveForm = $('[lay-filter="lig-saveForm"]'), _roleId = res.item.roleId;
                        _saveForm.find('input[name="roleId"]').val(_roleId);

                        lig.table({
                            elem: '[lay-filter="lig-user-table"]',
                            url: 'uc/user/page',
                            height:'270',
                            cols: [[
                                {title: '<span lig-lang="label-opt">操作</span>', toolbar: '#tpl-row-toolBar-user', align: 'left', width: 80, fixed: 'left'},
                                {title: '<span lig-lang="user-account">账号</span>', field: 'account', align: 'center', minWidth: 120},
                                {title: '<span lig-lang="user-userName">用户名</span>', field: 'userName', align: 'center', minWidth: 120}
                            ]]
                        }, {
                            entity: 'user',
                            primaryField: 'userId',
                            onTool: function (obj) {
                                var event = obj.event, data = obj.data;
                                if (event == 'lig-choose') {
                                    var exists = false;
                                    $('[lay-filter="lig-user-tag"]').find('button').each(function () {
                                        if (data.userId == $(this).attr('lay-id')) {
                                            lig.msg('用户已选择');
                                            exists = true;
                                            return false;
                                        }
                                    });

                                    if (!exists) {
                                        tag.add('lig-user-tag', {
                                            text:  data.userName ? data.userName : data.account
                                            , id: data.userId
                                        });
                                    }
                                }

                            }
                        });

                        lig.ajaxget({
                            url: 'uc/role/user/list',
                            data: {roleId: res.item.roleId},
                            success: function (result) {
                                if (result.data) {
                                    laytpl($('#tpl-user-tag').html()).render(result, function(html){
                                        $('[lay-filter="lig-user-tag"]').html(html);
                                        tag.render("lig-user-tag");
                                    });
                                }
                            }
                        });
                    },
                    onCompleted: function () {
                    }
                });
            });
        }

        function dialogSaveFormRes(options) {
            lig.dialog({
                content: $('#tpl-role-add').html(),
                title: options.title,
                area: ['50%', 'auto'],
                saveUrl: 'uc/role/add',
                onOpened: function () {
                    var _saveForm = $('[lay-filter="lig-saveForm"]');
                    _saveForm.find('input[name="parentId"]').val(options.parentId);
                },
                onCompleted: function () {
                    requestData();
                }
            });
        }

        function loadRoleResTree(roleId) {
            lig.ajaxget({
                url: 'uc/role/' + roleId + '/res/tree',
                success: function (res) {
                    if (!res.data) {
                        return;
                    }

                    _eleTree = eleTree.render({
                        elem: '[lay-filter="lig-role-res-tree"]',
                        highlightCurrent: true,
                        showLine: true,
                        defaultExpandAll: true,
                        defaultCheckedKeys: res.data.resIdList ? res.data.resIdList : [],
                        showCheckbox: true,
                        checkStrictly: true,
                        data: res.data.resTree ? res.data.resTree : [],
                        request: {
                            name: "name"
                        }
                    });

                    eleTree.on("nodeChecked(lig-role-res-tree)",function(d) {
                        if (d.isChecked) {
                            _eleTree.setChecked([d.data.currentData.id]);
                            checkedParent(d.node);
                            checkedChildren(d.data.currentData);
                        } else {
                            unCheckedChildren(d.data.currentData);
                        }
                    })
                }
            });
        }

        function checkedParent(node) {
            var parentNode = node.parent().parent();
            if (parentNode.hasClass('eleTree-node')) {
                _eleTree.setChecked([parentNode.attr('data-id')]);
                checkedParent(parentNode);
            }
        }

        function checkedChildren(data) {
            if (data.children) {
                $.each(data.children, function(i, it) {
                    _eleTree.setChecked([it.id]);
                    checkedChildren(it);
                });
            }
        }

        function unCheckedChildren(data) {
            if (data.children) {
                $.each(data.children, function(i, it) {
                    _eleTree.unCheckArrNodes([it.id]);
                    unCheckedChildren(it);
                });
            }
        }
    });
</script>